var UserToken = require('../db/user_tokens.js');

var express = require('express');
var simuSocket = express.Router();

var onlineUserCount = 0;
var onlineDeviceCount = 0;

var glUid2Res = {};
var MiniSecTimeoutForMsg = 15 * 1000;
var MiniSecTimeoutForAvail = 15 * 1000;

simuSocket.receiveReq = function (uid, device, res) {
    if(!glUid2Res.hasOwnProperty('' + uid)){
        glUid2Res[uid] = {};
    }
    if(!glUid2Res[uid].hasOwnProperty(device)){
        glUid2Res[uid][device] = {};
    }
    else if(glUid2Res[uid][device].res){
        glUid2Res[uid][device].res.json(new ERR('重复连接', 400));
        delete glUid2Res[uid][device].res;
    }
    var dataDev = glUid2Res[uid][device];
    dataDev.isMobile = device.substr(0, 2) == 'PC' ? false : true;
    dataDev.timeout = (new Date()).getTime() + MiniSecTimeoutForMsg;

    if(dataDev.onWaitMsg){
        var toSend = [];
        dataDev.onWaitMsg.forEach(function (onWaitMsg) {
            toSend.push(onWaitMsg.msg);
            var sender = onWaitMsg.res;
            if(sender && !sender._headerSent){
                sender.send(new PKG({}));
            }
        })
        delete dataDev.onWaitMsg;
        res.send(new PKG(toSend));
        return;
    }
    dataDev.res = res;
}
simuSocket.sendMsgTo = function(dataUid, device, msg, res){
    if(!dataUid.hasOwnProperty(device)){
        return false;
    }
    var dataDev = dataUid[device];
    if(!dataDev.res){   //不巧碰上连接刚返回
        if(!dataDev.onWaitMsg) dataDev.onWaitMsg = [];
        dataDev.onWaitMsg.push({msg:msg, res:res});
        return true;
    }

    dataDev.res.send(new PKG([msg]));
    dataDev.timeout = (new Date()).getTime() + MiniSecTimeoutForAvail;
    delete dataDev.res;

    if(!res._headerSent)res.send(new PKG({}));
    return true;
}
simuSocket.onSendMsg = function (body, res) {
    var dataUid = glUid2Res['' + body.destUid];
    if(!dataUid){
        res.json(new ERR('目标不在线！', 400));
        return;
    }
    var sendCount = 0;
    var device = body.destDevice;
    console.log(body.destUid);
    var msg = {uid:body.uid, device:body.device, content:body.content};
    if(!device){
        for(var dev in dataUid){
            if(simuSocket.sendMsgTo(dataUid, dev, msg, res)) ++sendCount;
        }
    }
    else{
        if(simuSocket.sendMsgTo(dataUid, device, msg, res)) ++sendCount;
    }
    if(!sendCount){
        res.json(new ERR('目标不在线！', 400));
    }
}
simuSocket.recvMsg = function (req, res) {
    if(!req.body || !req.body.token) {
        res.json(new ERR('token不能为空', 400));
        return ;
    }
    if(!req.body.device) {
        res.json(new ERR('device不能为空', 400));
        return ;
    }
    UserToken.checkLogin(req.body.token, function (err, loginInfo) {
        if (!loginInfo) {
            res.json(new ERR('请先登录', 403));
            return;
        }
        simuSocket.receiveReq(loginInfo.uid, req.body.device, res);
    });
}
simuSocket.post('/recvMsg', simuSocket.recvMsg);

simuSocket.sendMsg = function (req, res) {
    if(!req.body || !req.body.token) {
        res.json(new ERR('token不能为空', 400));
        return ;
    }
    if(!req.body.device) {
        res.json(new ERR('device不能为空', 400));
        return ;
    }
    if(!req.body.destUid) {
        res.json(new ERR('destUid不能为空', 400));
        return ;
    }
    UserToken.checkLogin(req.body.token, function (err, loginInfo) {
        if (!loginInfo) {
            res.json(new ERR('请先登录', 403));
            return;
        }
        req.body.uid = loginInfo.uid;
        simuSocket.getDeviceOfUser(req.body.destUid, function(e, data) {
            if(e) {
                console.log(e);
                res.json(new ERR('获取当前设备失败！', 400));
                return;
            }
            if(req.body.destDevice) {
                if(data.indexOf(req.body.destDevice) < 0) {
                    res.json(new ERR('当前设备未连接', 400));
                    return;
                } else {
                    simuSocket.onSendMsg(req.body, res);
                }
            } else {
                simuSocket.onSendMsg(req.body, res);
            }
        });
    });
}
simuSocket.post('/sendMsg', simuSocket.sendMsg);

simuSocket.onTimer = function () {
    try{
        checkTimeout();
    }
    catch(e){
        console.log(e);
    }
    setTimeout(simuSocket.onTimer, 100);
};
function checkTimeout() {
    var now = (new Date()).getTime();
    var curOnlineUser = 0;
    var curOnlineDev = 0;
    for (var uid in glUid2Res){
        ++curOnlineUser;
        var dataUid = glUid2Res[uid];
        var userOnlineDeviceCount = 0;
        for (var device in dataUid){
            var dataDev = dataUid[device];
            if(!dataDev.res && dataDev.timeout < now){   //返回后超过时间没有再连接

                if(dataDev.onWaitMsg){
                    dataDev.onWaitMsg.forEach(function(onWaitMsg){
                        var waiter = onWaitMsg.res;
                        if(!waiter._headerSent){
                            waiter.json(new ERR('发送超时！', 400));
                        }
                    });
                }
                delete dataUid[device];
                continue;
            }
            ++userOnlineDeviceCount;
            if(dataDev.timeout > now){
                continue;
            }
            dataDev.res.send(new PKG([]));
            delete dataDev.res;
            dataDev.timeout = now + MiniSecTimeoutForAvail;
        }
        if(userOnlineDeviceCount <= 0){
            delete glUid2Res[uid];
        }

        curOnlineDev += userOnlineDeviceCount;
    }

    onlineUserCount = curOnlineUser;
    onlineDeviceCount = curOnlineDev;
}
setTimeout(simuSocket.onTimer, 100);

simuSocket.getDeviceOfUser = function (uid, cb) {
    var devices = [];
    for (var i in glUid2Res[uid]) {
        devices.push(i);
    }
    cb(null,devices);
}

simuSocket.start = function (req, res) {

}

module.exports = simuSocket;